package com.rui.fourthly.day0929_test_pic;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private static final int SUCCESS = 200;
    private static final int ERROR = 201;
    private static final int FAULT = 199;
    private ImageView image;
    private String path = "http://172.17.28.21:8080/qi.jpg";
    private Handler hd = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SUCCESS:
                    Bitmap bitmap = (Bitmap) msg.obj;
                    image.setImageBitmap(bitmap);
                    break;
                case ERROR:
                    int code = (int) msg.obj;
                    Toast.makeText(MainActivity.this, "错误码=" + code, Toast.LENGTH_SHORT).show();
                    break;
                case FAULT:
                    Toast.makeText(MainActivity.this, "异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = (ImageView) findViewById(R.id.myimage);
        new Thread(new Runnable() {
            @Override
            public void run() {
                getPic();
            }
        }).start();
    }

    private void getPic() {
        try {
            URL url = new URL(path);
            HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
            openConnection.setConnectTimeout(5000);
            openConnection.setConnectTimeout(5000);
            int responseCode = openConnection.getResponseCode();
            if (responseCode == 200) {
                InputStream inputStream = openConnection.getInputStream();
                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                hd.obtainMessage(SUCCESS, bitmap).sendToTarget();
            } else {
                hd.obtainMessage(ERROR, responseCode).sendToTarget();
            }
        } catch (Exception e) {
            e.printStackTrace();
            hd.obtainMessage(FAULT).sendToTarget();
        }
    }

}
